package cn.edu.zzuli.nothinglink.service.impl;

import cn.edu.zzuli.nothinglink.constant.TokenConst;
import cn.edu.zzuli.nothinglink.entity.R;
import cn.edu.zzuli.nothinglink.entity.Students;
import cn.edu.zzuli.nothinglink.mapper.ClassesMapper;
import cn.edu.zzuli.nothinglink.mapper.StudentsMapper;
import cn.edu.zzuli.nothinglink.service.StudentsService;
import cn.edu.zzuli.nothinglink.utils.RedisUtil;
import cn.edu.zzuli.nothinglink.utils.TokenUtil;
import cn.edu.zzuli.nothinglink.vo.StuLoginVo;
import cn.edu.zzuli.nothinglink.vo.StuRegisterVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author suzyyy
 * @since 2021-04-08
 */
@Service
public class StudentsServiceImpl extends ServiceImpl<StudentsMapper, Students> implements StudentsService {

    @Resource
    StudentsMapper studentsMapper;

    @Resource
    ClassesMapper classesMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public R stuLogin(StuLoginVo vo) {
        Students students = null;
        if (vo.getUsername() != null)
            students = studentsMapper.selectOne(
                    new LambdaQueryWrapper<Students>()
                            .eq(Students::getStuUsername, vo.getUsername())
            );
        else
            students = studentsMapper.selectOne(
                    new LambdaQueryWrapper<Students>()
                            .eq(Students::getStuEmail, vo.getUsername())
            );


        if (students != null && students.getStuPassword().equals(vo.getPassword())) {
            Integer belongClassId = students.getBelongClassId();
            if (belongClassId != 0) students.setClassName(classesMapper.selectById(belongClassId).getClassRealName());
            //验证成功后，返回创建的 token
            return R.success().add("stu", students.setStuPassword("")).add("token", getToken(students));
        }
        return R.error().add("error", "请检查用户/邮箱/密码，是否有误！");
    }

    @Override
    public R stuRegister(StuRegisterVo vo) {
        if (StringUtils.isEmpty(vo.getAvatar())) {
            vo.setAvatar("https://nothing-link.oss-cn-beijing.aliyuncs.com/b6b2e4c9-4333-443a-84da-d60632f3f949.png");
        }

        //属性复制，因为写前端的时候比较随意，导致参数不一致，否则用spring的BeanUtils.copyProperties()更方便
        //现在改为在学生个人页面绑定班级
        Students stu = new Students().setStuName(vo.getName()).setBelongClassId(0)
                .setStuPassword(vo.getPassword()).setStuGender(vo.getGender())
                .setStuPhone(vo.getPhone()).setStuAvatar(vo.getAvatar())
                .setStuEmail(vo.getEmail()).setStuUsername(vo.getUsername())
                .setStuNumber(vo.getStuNumber());

        if (save(stu)) {
            //验证成功后，返回创建的 token
            return R.success().add("stu", stu.setStuPassword("")).add("token", getToken(stu));
        }
        return R.error().add("error", "注册失败");
    }

    public String getToken(Students stu) {
        //验证成功后，返回创建的 token
        Long currentTimeMillis = System.currentTimeMillis();
        String token= TokenUtil.sign(stu.getStuId().toString(),TokenConst.STU_ROLE.getKey(), currentTimeMillis);
        //设置token信息到redis中，方便进行校验
        redisUtil.set(TokenConst.STU_REFRESH_TOKEN.getKey() + stu.getStuId().toString(),
                currentTimeMillis,TokenUtil.REFRESH_EXPIRE_TIME);
        return token;
    }

    @Override
    public boolean delbatch(List<Integer> stuIds) {

        List<Students> students = stuIds.stream()
                .map(id -> new Students().setStuId(id).setBelongClassId(0))
                .collect(Collectors.toList());
        //批量修改学生的班级id
        return updateBatchById(students);
    }

    @Override
    public Students findOneUserByInfo(Map<String, Object> info) {
        return studentsMapper.findStuByInfo(info);
    }

    @Override
    public boolean delStuFromTheClass(Integer stuId) {
        if (this.updateById(new Students().setStuId(stuId).setBelongClassId(0)))
            return true;
        return false;
    }
}
